package com.wbp.cms.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.core.service.image.ImageUploadYunManager;
import com.wbp.cms.core.util.ImageUploadUtil;


/**
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月25日 下午11:21:27 
 */
@Controller("imageUploadController")
@RequestMapping("/wgimageupload")
public class ImageUploadController  extends BaseController{

  private static Logger logger = Logger.getLogger(ImageUploadController.class) ;
  
  @Resource(name="imageUploadYunManager")
  private ImageUploadYunManager  imageUploadYunManager ;
  
  
   @RequestMapping(value="/get",method = {RequestMethod.GET,RequestMethod.POST}  ,produces = "application/json;charset=UTF-8" )
   @ResponseBody
   public String  doGetImageUploadUrl(HttpServletRequest request,MultipartFile file){
     Map<String,String> map = this.getParameters(request) ;
     //System.out.println(map);
       long size = file.getSize() ;
       long maxSize =90*1024 ;
      //  System.out.println("file size: "+size);
       if(size > maxSize ){  // 图片大小要小于90kb 
           return JsonUtils.toJson(Result.buildError("图片大小在90kb以内")) ;
       }
     String fileName = ( map.get("name")==null?"":map.get("name") )  ;
     try {
          BufferedImage bi =  ImageIO.read(file.getInputStream() ) ;
          if(bi.getWidth() >100 || bi.getHeight() >100)
             return JsonUtils.toJson(Result.buildError("图片长宽在100*100以内")) ;
           
          map =  imageUploadYunManager.getUploadYunService().uploadFile(file.getBytes(), ImageUploadUtil.getTime()+fileName) ;
      } catch (IOException e) {
        logger.error("doGetImageUploadUrl exception:",e);
         return JsonUtils.toJson(Result.buildError("上传出错")) ;
      }
  //   System.out.println(map);
     return  JsonUtils.toJson(Result.buildSuccess(map.get("ossurl"))) ;
   }
}
